package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.CustomerReturnListDao;
import com.atguigu.jxc.dao.CustomerReturnListGoodsDao;
import com.atguigu.jxc.entity.CustomerReturnList;
import com.atguigu.jxc.entity.ReturnListGoods;
import com.atguigu.jxc.entity.User;
import com.atguigu.jxc.service.GoodsService;
import com.atguigu.jxc.service.CustomerReturnListService;
import com.atguigu.jxc.to.CustomerCountTo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * @author: lshuaib
 * @create: 2021-03-08 15:15
 * @description:
 */
@Service
public class CustomerReturnListServiceImpl implements CustomerReturnListService {
    @Resource
    CustomerReturnListDao customerReturnListDao;
    @Resource
    CustomerReturnListGoodsDao customerReturnListGoodsDao;
    @Resource
    GoodsService goodsService;

    @Override
    @Transactional
    public void save(String returnNumber, CustomerReturnList customerReturnList, String returnListGoodsList, HttpSession session) {
        Gson gson=new Gson();
        customerReturnList.setReturnNumber(returnNumber);
        User user = (User) session.getAttribute("currentUser");
        customerReturnList.setUserId(user.getUserId());
        customerReturnListDao.saveReturnList(customerReturnList);
        List<ReturnListGoods> returnListGoods = gson.fromJson(returnListGoodsList, new TypeToken<List<ReturnListGoods>>() {
        }.getType());
        returnListGoods.forEach(entity->{
            entity.setReturnListId(customerReturnList.getCustomerReturnListId());
            customerReturnListGoodsDao.add(entity);
            goodsService.addStock(entity.getGoodsCode(),entity.getGoodsNum());
        });

    }

    @Override
    public List<Map> count(CustomerCountTo customerCountTo) {
        String codeOrName = customerCountTo.getCodeOrName();
        if(null!=codeOrName &&  !"".equals(codeOrName)){
            try {
                int i = Integer.parseInt(codeOrName);
                customerCountTo.setStatus(1);
            }catch (Exception e){
                customerCountTo.setStatus(2);
            }
        }

        List<Map> list = customerReturnListGoodsDao.count(customerCountTo);
        return list;
    }
}
